package com.wk.springboot.util;

import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryAction;

/**
 * @Classname EsUtils
 * @Description Es常规操作的工具类
 * @Date 2020/5/29 16:08
 * @Author by weikai
 */
public class EsUtils {

  /**
   * 判断索引是否存在
   *
   * @param client
   * @param indexName
   * @return
   */
  public static boolean isExistsIndex(Client client, String indexName) {
    IndicesExistsResponse response =
        client.admin().indices().exists(
            new IndicesExistsRequest().indices(new String[]{indexName})).actionGet();
    return response.isExists();
  }

  /**
   * 判断索引指定类型是否存在
   *
   * @param client
   * @param indexName
   * @param indexType
   * @return
   */
  public static boolean isExistsType(Client client, String indexName, String indexType) {
    TypesExistsResponse response =
        client.admin().indices().typesExists(
            new TypesExistsRequest(new String[]{indexName}, indexType)).actionGet();
    return response.isExists();
  }

  public static void createEmptyIndex(Client client, String indexName) {
    CreateIndexRequestBuilder cib =
        client.admin().indices().prepareCreate(indexName);
    cib.execute().actionGet();

  }

  //在导入数据时定期清理缓存
  public static boolean clearIndicesCache(Client client, String indexName) {
    ClearIndicesCacheResponse response = null;
    try {
      //version 5
      response = client.admin().indices()
          .clearCache(new ClearIndicesCacheRequest(indexName).fieldDataCache(true)).actionGet();
      if (response.getFailedShards() > 0) {
        return false;
      }
      return true;
    } catch (Exception e) {
      ESLog.LOG.error("清理缓存出错", e);
    }
    return false;
  }


  //清空索引中的数据相当于truncate table
  public static void cleanIndex(Client client, String index, String type) {
    long start = System.currentTimeMillis();
    ESLog.LOG.info("删除 {} : {} 中数据开始:{}", index, type, start);
    DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
        .filter(QueryBuilders.typeQuery(type))
        .source(index)
        .get();
    long end = System.currentTimeMillis();
    ESLog.LOG.info("删除 {} : {} 中数据结束，用时:{}", index, type, (end - start));
  }




  //用于在批量导入时设置索引的刷新时间间隔和复本数量
  public static void changeIndexProperties(String index, Client client, String refresh_interval, String number_of_replicas) {
    client.admin()
        .indices()
        .prepareUpdateSettings(index)
        .setSettings(
            Settings.builder()
                //设置索引自动刷新，做实时搜索时有用；对于大量搜索，没有用
                .put("index.refresh_interval", refresh_interval)
                //数据备份数，如果是一台机器，则设置为0
                .put("index.number_of_replicas", number_of_replicas)).get();
  }
}
